package com.lqh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lqh.mapper.ClazzMapper;
import com.lqh.mapper.EmpMapper;
import com.lqh.pojo.Clazz;
import com.lqh.pojo.ClazzQueryParam;
import com.lqh.pojo.PageResult;
import com.lqh.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public PageResult<Clazz> pqgeQuery(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        List<Clazz> list = clazzMapper.pageQuery(clazzQueryParam);
        LocalDate now = LocalDate.now();
        //班级状态 - 未开班 , 在读 , 已结课
        for (Clazz clazz : list) {
            if(clazz.getBeginDate().isAfter(now)){
                clazz.setStatus("未开班");
            }
            else if(clazz.getBeginDate().isBefore(now) && clazz.getEndDate().isAfter(now)){
                clazz.setStatus("在读");
            }
            else if(clazz.getEndDate().isBefore(now)){
                clazz.setStatus("已结课");
            }
        }
        Page<Clazz> page = (Page<Clazz>) list;
        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        clazzMapper.deleteById(id);
    }

    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        if(clazz.getMasterId()==null){
            clazz.setMasterId(1);
        }
        clazzMapper.addClazz(clazz);
    }

    @Override
    public Clazz searchById(Integer id) {
        return clazzMapper.searchById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClazz(Clazz clazz) {
        clazzMapper.deleteById(clazz.getId());
        clazzMapper.addClazz(clazz);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.clazzList();
    }
}
